"""
用户相关的数据验证模式
"""
from marshmallow import Schema, fields, validate, validates, ValidationError, post_load
from app.models.user import UserRole

class UserSchema(Schema):
    """用户数据验证模式"""
    id = fields.Integer(dump_only=True)
    username = fields.String(required=True, validate=validate.Length(min=3, max=50))
    email = fields.Email(required=True)
    password = fields.String(required=True, load_only=True, validate=validate.Length(min=6))
    full_name = fields.String(allow_none=True)
    role = fields.String(validate=validate.OneOf([role.value for role in UserRole]))
    is_active = fields.Boolean()
    created_at = fields.DateTime(dump_only=True)
    
    @validates('username')
    def validate_username(self, value):
        """验证用户名"""
        from app.models.user import User
        user = User.query.filter_by(username=value).first()
        if user:
            raise ValidationError('用户名已存在')
    
    @validates('email')
    def validate_email(self, value):
        """验证邮箱"""
        from app.models.user import User
        user = User.query.filter_by(email=value).first()
        if user:
            raise ValidationError('邮箱已存在')

class UserUpdateSchema(Schema):
    """用户更新数据验证模式"""
    full_name = fields.String(allow_none=True)
    email = fields.Email()
    role = fields.String(validate=validate.OneOf([role.value for role in UserRole]))
    is_active = fields.Boolean()
    
    @validates('email')
    def validate_email(self, value):
        """验证邮箱"""
        from app.models.user import User
        user = User.query.filter_by(email=value).first()
        if user and user.id != self.context.get('user_id'):
            raise ValidationError('邮箱已存在')

class LoginSchema(Schema):
    """登录数据验证模式"""
    username = fields.String(required=True)
    password = fields.String(required=True)

class PasswordChangeSchema(Schema):
    """密码更改数据验证模式"""
    old_password = fields.String(required=True)
    new_password = fields.String(required=True, validate=validate.Length(min=6))
    
    @validates('new_password')
    def validate_new_password(self, value):
        """验证新密码"""
        if value == self.context.get('old_password'):
            raise ValidationError('新密码不能与旧密码相同') 